package com.topdt.jbpm.web.struts.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.web.SessionInfo;
import com.thx.common.web.WebConstant;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.model.Todo;
import com.topdt.jbpm.model.WorkOpinion;
import com.topdt.jbpm.service.CommentService;
import com.topdt.jbpm.service.JbpmService;
import com.topdt.jbpm.web.SessionUserUtil;

/**
 *
 * @创建日期 2013-4-19 <br>
 * @作者: 王阿敏 <br>
 * @模块: 起草工作意见<br>
 * @描述: <br>
 * @修改历史:_zili 2015年4月17日 <br>
 */
@Namespace("/workflow")
@Action(value = "comment", results = {
		@Result(name = "showComment", location = "/pages/workflow/templates/comment.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" }),
		@Result(name = "jsonStr", type = "json", params = { "root", "jsonStr" }) })
@Controller
@Scope("prototype")
public class CommentAction extends CurdAction<WorkOpinion> {

	private static final long serialVersionUID = 1L;
	@Autowired
	private CommentService commentService;// 页面输出
	@Autowired
	private JbpmService jbpmService;// 页面输出
	private WorkOpinion option;
	private String opinionId;//
	private String jsonStr;

	/**
	 * 跳转到添加意见页面 建立日期 : June 25, 2013 5:41:50 PM<br>
	 * 作者 : wangamin<br>
	 *
	 * @return
	 */
	public String showComment() {
		logger.debug("<进入>:showComment方法   跳转到添加意见页面");
		User user = SessionUserUtil.getCurrentUser();
		String userId = user.getId();
		entity = commentService.getWorkOPioionsByTodoIdPid(entity.getWorkId(), userId);
		return "showComment";
	}

	/**
	 * 添加意见 建立日期 : June 25, 2013 5:41:50 PM<br>
	 * 作者 : wangamin<br>
	 *
	 * @return
	 * @throws Exception
	 */
	public String saveUpdateInfo() {
		logger.debug("<进入>:showComment方法   新增或修改意见");
		User user = SessionUserUtil.getCurrentUser();
		String comId = AppContext.getCurrentComId();
		logger.info("线程id=" + Thread.currentThread().getId() + "保存意见取到的企业id" + comId);
		if (StringUtils.isBlank(comId) && getSession().getAttribute(WebConstant.KEY_USER) != null) {// zhangyong20160302
			comId = ((SessionInfo) (getSession().getAttribute(WebConstant.KEY_USER))).getComId();
		}
		List<Object[]> objs = new ArrayList<Object[]>();

		if (StringUtils.isNotBlank(entity.getOpinionId())) {
			WorkOpinion option = new WorkOpinion();
			option = commentService.getWorkOPioionsByOpinionId(entity.getOpinionId());
			if (option != null && entity != null) {
				try {
					option.setOpinionContent(entity.getOpinionContent());
					option.setSignTime(new Date());
				} catch (Exception e) {
					logger.error("<错误>:修改意见失败", e);
				}
			}
			if (StringUtils.isNotBlank(option.getOpinionContent())) {// 意见如果为空，不要保存zhangyong
																		// 20141204
				commentService.update(option);
			}
		} else {
			// wangxufeng edit 2015-02-03 防止重复保存数据
			WorkOpinion temp = commentService.getWorkOPioionsByTodoIdPid(entity.getTodoId(), user.getId());
			if (temp == null) {
				Todo todo =null;
				if (StringUtils.isBlank(entity.getTodoId())) {
					if (StringUtils.isNotBlank(entity.getWorkId())) {
						todo = jbpmService.findTodoByWorkAndUser(entity.getWorkId(), user.getId());
					}
				} else {
					todo = jbpmService.getTodoById(entity.getTodoId());
				}
				// wangxufeng edit 2015-02-08
				// 防止多人的时候当前用户完成待办，但是节点中还有当前人的这种情况下todo为null的情况
				if (todo != null) {
					entity.setTodoId(todo.getTodoId());
					entity.setSignTime(new Date());
					entity.setActivityName(todo.getActivityName());
					entity.setSigerId(user.getId());
					entity.setSigerName(user.getName());
					entity.setCompanyId(comId);
					if (StringUtils.isNotBlank(entity.getOpinionContent())) {// 意见如果为空，不要保存zhangyong
																				// 20141204
						commentService.saveorUpdate(entity);
					}
				}
			} else {
				temp.setOpinionContent(entity.getOpinionContent());
				temp.setSignTime(new Date());
				if (StringUtils.isNotBlank(entity.getOpinionContent())) {
					commentService.update(temp);
				}
			}
		}

		jsonStr = com.alibaba.fastjson.JSON.toJSONString(entity.getOpinionId());
		return "jsonStr";
	}

	/**
	 * 根据todoId获取意见信息 建立日期 : June 25, 2013 5:41:50 PM<br>
	 * 作者 : wangamin<br>
	 *
	 * @return
	 */
	public String getOptionBytodoIdAndUserId() {
		logger.debug("<进入>:getOptionBytodoIdAndUserId方法   通过todoId获取意见信息");
		User user = SessionUserUtil.getCurrentUser();
		String userId = user.getId();
		option = commentService.getWorkOPioionsByTodoIdPid(entity.getTodoId(), userId);
		jsonStr = com.alibaba.fastjson.JSON.toJSONString(option);
		return "jsonStr";
	}



	public WorkOpinion getOption() {
		return option;
	}

	public void setOption(WorkOpinion option) {
		this.option = option;
	}

	public String getOpinionId() {
		return opinionId;
	}

	public void setOpinionId(String opinionId) {
		this.opinionId = opinionId;
	}

	public String getJsonStr() {
		return jsonStr;
	}

	public void setJsonStr(String jsonStr) {
		this.jsonStr = jsonStr;
	}

	/**
	 * 根据todoId获取意见信息 建立日期 : June 25, 2013 5:41:50 PM<br>
	 * 作者 : wangamin<br>
	 *
	 * @return
	 */
	public void getOptionBytodoIdAndUserIdApp() {
		logger.debug("<进入>:getOptionBytodoIdAndUserIdApp方法   通过todoId获取意见信息");
		String userId = getRequest().getParameter("userId");
		option = commentService.getWorkOPioionsByTodoIdPid(entity.getTodoId(), userId);
		String json = com.alibaba.fastjson.JSON.toJSONString(option == null ? "" : option);
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(json);
		} catch (IOException e) {
			logger.error("<错误>:获取意见信息失败", e);
		}
	}

	public void saveUpdateInfoCustomApp() {
		logger.debug("<进入>:saveUpdateInfoCustomApp方法   修改意见");
		User user = SessionUserUtil.getCurrentUser();
		String comId = AppContext.getCurrentComId();
		String opinionJson = "";
		// 更新意见
		if (StringUtils.isNotBlank(entity.getOpinionId())) {
			WorkOpinion option = new WorkOpinion();
			option = commentService.getWorkOPioionsByOpinionId(entity.getOpinionId());
			if (option != null && entity != null) {
				try {
					option.setOpinionContent(entity.getOpinionContent());
					option.setSignTime(new Date());
					commentService.update(option);
				} catch (Exception e) {
					logger.error("<错误>:修改意见失败", e);
				}
			}
			opinionJson = com.alibaba.fastjson.JSON.toJSONString(option);
		} else {
			// wangxufeng edit 2015-02-03 防止重复保存数据
			Todo todo = new Todo();
			WorkOpinion temp = commentService.getWorkOPioionsByTodoIdPid(entity.getTodoId(), user.getId());
			// 当前待办没有添加过意见
			if (temp == null) {
				if (StringUtils.isBlank(entity.getTodoId())) {
					if (StringUtils.isNotBlank(entity.getWorkId())) {
						todo = jbpmService.findTodoByWorkAndUser(entity.getWorkId(), user.getId() + "");
					}
				} else {
					todo = jbpmService.getTodoById(entity.getTodoId());
				}
				// wangxufeng edit 2015-02-08
				// 防止多人的时候当前用户完成待办，但是节点中还有当前人的这种情况下todo为null的情况
				if (todo != null) {
					entity.setTodoId(todo.getTodoId());
					entity.setSignTime(new Date());
					entity.setActivityName(todo.getActivityName());
					entity.setSigerId(user.getId() + "");
					entity.setSigerName(user.getName());
					entity.setCompanyId(comId);
					if (StringUtils.isNotBlank(entity.getOpinionContent())) {// 意见如果为空，不要保存zhangyong
																				// 20141204
						commentService.saveorUpdate(entity);
						// SimpleDateFormat sdf = new
						// SimpleDateFormat("yyyy-MM-dd HH:mm");
						// objs.add(new
						// Object[]{entity.getActivityName(),entity.getOpinionContent(),sdf.format(entity.getSignTime()),entity.getSigerName(),entity.getOpinionId(),p.getReserve1()});
					}
					opinionJson = com.alibaba.fastjson.JSON.toJSONString(entity);
				}
			} else {
				temp.setOpinionContent(entity.getOpinionContent());
				temp.setSignTime(new Date());
				commentService.update(temp);
				opinionJson = com.alibaba.fastjson.JSON.toJSONString(temp);
			}
		}
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(opinionJson);

		} catch (IOException e) {
			logger.error("<错误>:修改意见失败", e);
		}
	}

}

/**
 *
 * @author Wangxufeng
 * @date 2014-12-10
 * @project saasoa
 * @description 比较器，用于对list排序
 */
class ComparatorOption implements Comparator<Object[]> {
	/**
	 * 按照日期排序
	 */
	@Override
	public int compare(Object[] obj, Object[] nextObj) {
		String signTime = obj[2].toString();
		String signTime2nextObj = nextObj[2].toString();
		int flag = signTime.compareTo(signTime2nextObj);
		return flag >= 0 ? -1 : 1;
	}
}
